import { Delete, List, Save, Update } from '@/services/system/menu';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { BetaSchemaForm, ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { FORM_COLUMNS, TABLE_COLUMNS } from './data';
export default () => {
  useEffect(() => {
    getMenuListFn();
  }, []);
  const [MenuDatas, setMenuDatas]: any = useState({});
  async function getMenuListFn() {
    let res = await List();
    setMenuDatas([
      {
        id: 0,
        title: '根目录',
      },
      ...(res?.data || []),
    ]);
  }
  const [flag, setflag] = useState(false);
  const [formDatas, setformDatas]: any = useState('');
  const [editRowData, seteditRowData]: any = useState({});
  const [modelTitle, setmodelTitle] = useState('');
  async function EditFn(row: any) {
    await setmodelTitle('编辑');
    await seteditRowData({ ...row });
    await setflag(true);
    // 这里不太会写react，暂时这么搞下
    setTimeout(() => {
      formRef?.current?.setFieldsValue({
        ...row,
      });
    }, 0);
  }
  const columns: ProColumns[] = [
    ...TABLE_COLUMNS,
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: (_, row) => [
        <Button key="edit" type="link" onClick={() => EditFn(row)}>
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="是否确定删除该行?"
          onConfirm={async () => {
            await Delete({ id: row.id });
            actionRef.current.reload(); // 刷新表格
            getMenuListFn();
          }}
          onCancel={() => {}}
          okText="确定"
          cancelText="取消"
        >
          <Button type="text" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];
  const actionRef: any = useRef<ActionType>();
  const formRef: any = useRef();
  return (
    <>
      <ProTable
        actionRef={actionRef}
        columns={columns}
        request={async () => {
          let { data } = await List();
          return Promise.resolve({
            data: data,
            success: true,
          });
        }}
        bordered
        rowKey="id"
        pagination={false}
        // 搜索表单参数
        search={{
          layout: 'horizontal',
          defaultCollapsed: true,
        }}
        dateFormatter="string"
        toolbar={{
          title: '菜单管理',
          tooltip: '',
        }}
        toolBarRender={() => [
          <BetaSchemaForm
            form={formDatas}
            formRef={formRef}
            open={flag}
            grid={true}
            trigger={
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  setmodelTitle('新增');
                }}
              >
                新增
              </Button>
            }
            onOpenChange={(flag) => {
              setflag(flag);
            }}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 17 }}
            layout={'horizontal'}
            layoutType={'ModalForm'}
            onFinish={async () => {
              formRef.current?.validateFieldsReturnFormatValue?.().then(async (values: any) => {
                let query = { ...values, pid: values.parentId };
                delete query.parentId;
                if (modelTitle == '编辑') {
                  await Update({ ...query, id: editRowData.id });
                  message.success('编辑成功');
                } else {
                  await Save({ ...query });
                  message.success('新增');
                }
                actionRef.current.reload(); // 刷新表格
                getMenuListFn();
                setflag(false);
              });
            }}
            // 弹窗参数
            modalProps={{ destroyOnClose: true, width: 1000, title: modelTitle }}
            columns={[
              {
                title: '上级菜单',
                dataIndex: 'parentId',
                valueType: 'treeSelect',
                initialValue: 0,
                formItemProps: {
                  rules: [{ required: true, message: '请选择上级菜单' }],
                },
                colProps: {
                  xs: 12,
                  md: 12,
                },
                fieldProps: {
                  placeholder: '请选择上级菜单',
                  fieldNames: { label: 'title', value: 'id', children: 'children' },
                  options: MenuDatas,
                },
              },
              {
                title: '类型',
                dataIndex: 'type',
                valueType: 'radio',
                hideInSearch: true,
                formItemProps: {
                  rules: [{ required: true }],
                },
                initialValue: 1,
                fieldProps: {
                  options: [
                    { label: '目录', value: 0 },
                    { label: '菜单', value: 1 },
                    { label: '按钮', value: 2 },
                  ],
                  onChange: (event: any) => {
                    console.log(event.target.value, 'value', formRef.current);
                  },
                },
                width: 'md',
                colProps: {
                  xs: 12,
                  md: 12,
                },
              },
              ...FORM_COLUMNS,
            ]}
          />,
        ]}
      />
    </>
  );
};
